﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Flower.Client;
using Flower.Services;
using Spring.Context;
using Spring.Context.Support;
using Flower.Logging;
using Spring.Objects.Factory;

namespace Flower.Processor
{
    internal static class ApplicationContext
    {
        private const string CONFIG_FILE_NAME = "Flower.Processor.config";
        private const string FLOWER_CLIENT_NAME = "flowerClient";
        private const string STATE_SERVICE_NAME = "stateService";
        private const string PROCESSOR_SETTINGS_NAME = "processorSettings";

        private static readonly Log Log = LogManager.CreateLog(typeof(ApplicationContext).Name);

        private static readonly IApplicationContext AppContext;

        static ApplicationContext()
        {
            try
            {
                AppContext =
                    new XmlApplicationContext
                    (
                        string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"\", CONFIG_FILE_NAME)
                    );
            }
            catch (Exception ex)
            {
                Log.Fatal("Failed to initialize application context.", ex);
                throw;
            }
        }

        public static IFlowerClient GetDirectoryClient()
        {
            return (IFlowerClient)AppContext.GetObject(FLOWER_CLIENT_NAME);
        }

        public static IStateService GetStateService()
        {
            try
            {
                return (IStateService)AppContext.GetObject(STATE_SERVICE_NAME);
            }
            catch (NoSuchObjectDefinitionException)
            {
                return null;
            }
        }

        public static ProcessorSettings GetProcessorSettings()
        {
            return (ProcessorSettings)AppContext.GetObject(PROCESSOR_SETTINGS_NAME);
        }
    }
}
